<!--
 * @Author: baoyiwen 511530203@qq.com
 * @Date: 2025-05-13 16:35:04
 * @LastEditors: baoyiwen 511530203@qq.com
 * @LastEditTime: 2025-05-13 17:47:51
 * @FilePath: \neilao-mobile\src\views\authpage\auth.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="auth-root">
    <van-loading size="24px" vertical v-if="isLoding">登录中...</van-loading>
  </div>
</template>

<script setup>
import { ref } from "vue";
import dd from "gdt-jsapi";
import { showSuccessToast, showFailToast } from "vant";
import { useRouter } from "vue-router";
import { getUserInfo, getTokenByCode, getDataToken } from "../../api/index";
import {
  setToken,
  setUserInfo,
  setDataToken,
  clearAllUserInfo,
} from "../../utils/userInfo";
const router = useRouter();
const isLoding = ref(true);
dd.getAuthCode({})
  .then((res) => {
    // const data = JSON.parse(res.data.data);
    const authCode = res.code;
    getTokenByCode(authCode)
      .then((res) => {
        if (res.data.code === 200) {
          const data = JSON.parse(res.data.data);
          const token = data.token;
          setToken(token);
          getUserInfo(token)
            .then((res) => {
              if (res.data.code === 200) {
                setUserInfo(res.data.data);
                getDataToken(token)
                  .then((res) => {
                    if (res.data.code === 200) {
                      router.push("/home");
                      setDataToken(res.data.message);
                    } else {
                      clearAllUserInfo();
                      router.push("/login");
                    }
                  })
                  .catch((err) => {
                    clearAllUserInfo();
                    showFailToast("获取数据token失败!");
                    router.push("/login");
                  });
              } else {
                clearAllUserInfo();
                router.push("/login");
              }
            })
            .catch((err) => {
              clearAllUserInfo();
              showFailToast("获取用户信息失败!");
              router.push("/login");
            });
        } else {
          clearAllUserInfo();
          showFailToast("获取token失败!");
          router.push("/login");
        }
      })
      .catch((err) => {
        clearAllUserInfo();
        showFailToast("获取token失败!");
        router.push("/login");
      });
  })
  .catch((err) => {
    clearAllUserInfo();
    showFailToast("获取授权失败!");
    router.push("/login");
  })
  .finally(() => {
    isLoding.value = false;
  });
</script>

<style scoped lang="less">
.auth-root {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>
